import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Scanner;

public class StartServer {

	static String bastPath = "";
	static List<String> notCopy = new ArrayList<String>();
	static boolean isFirst = false;
	static String target = "";

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			new StartServer().loadProperties();
			Scanner scan = new Scanner(System.in);
			System.out.println("确认配置是否正确，请选择：Y/N");
			String confirm = scan.next();
			if (confirm.toUpperCase().equals("Y")) {
				copyFile("E:\\exercise_space\\ExtWeb\\WebRoot");
				System.out.println("文件复制完毕，开始启动服务！");
			} else {
				System.out.println("取消了文件手复制！");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	private static void copyFile(String path) throws IOException {
		File file = new File(path);
		File f[] = file.listFiles();
		for (File fl : f) {
			if (fl.isFile()) {
				String basePath = fl.getPath().substring(
						StartServer.bastPath.length(),
						fl.getPath().lastIndexOf("\\") + 1);
				File floder = new File(target + basePath);
				if (!floder.exists())
					floder.mkdirs();
				File temp = new File(target + basePath + fl.getName());
				temp.createNewFile();
				FileInputStream fis = null;
				FileOutputStream fos = null;
				try {
					fis = new FileInputStream(fl);
					fos = new FileOutputStream(temp);
					int i = -1;
					while ((i = fis.read()) != -1) {
						fos.write(i);
					}
					System.out.println("copy file " + fl.getPath() + " to "
							+ target + basePath + "successfully.");
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} finally {
					if (fis != null) {
						fis.close();
					}
					if (fos != null) {
						fos.close();
					}
				}
			} else {
				if (!notCopy.contains(fl.getPath()) && !isFirst)
					copyFile(fl.getPath());
			}
		}
	}

	private void loadProperties() {
		Properties property = new Properties();
		try {
			property.load(this.getClass().getResourceAsStream(
					"/deploy.properties"));
			StartServer.bastPath = property.getProperty("source");
			StartServer.target = property.getProperty("target");
			String temp = property.getProperty("notcopy");
			for (String path : temp.split(",")) {
				StartServer.notCopy.add(path);
			}
			System.out.println("配置选项分别是：source=" + StartServer.bastPath
					);
			System.out.println("\ttarget=" + StartServer.target);
			System.out.println("\tnotcopy="+temp);
			System.out.println("配置文件读取完毕。");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}
